using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class GenArtPrefabBattleCharacter : GenArtPrefabLevelCharacter
    {
        public override ArtModeGenType genPrefabType => ArtModeGenType.BattleCharacter;

        protected override string outputBasePath => "Res/02_Character";
        protected override int prefabLayer => (int)LayerConsts.Character;
        protected override string entityGenConfigPath => $"Assets/EditorConfig/ArtToolConfig/EntityGen/Character/{entityName}.asset";
        protected override string defaultGenConfigPath => "Assets/EditorConfig/ArtToolConfig/EntityGen/Common/Entity_LevelCharacter.asset";

        public override void GenArtPrefab(bool withAnimator, bool forceReplaceOld)
        {
            string EntityPath = Path.Combine(Application.dataPath, this.outputBasePath);
            string prefabName = ArtPrefabToolConstant.Prefab_Sign_Battle + entityName;

            string destCharPath = Path.Combine(EntityPath, entityName);
            if (!Directory.Exists(destCharPath))
            {
                Directory.CreateDirectory(destCharPath);
            }

            var destAssetPath = GetOutputPrefabPath(entityName, prefabName);
            GameObject oldDestCharPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(destAssetPath);
            //如果目标已经有Prefab，弹个替换确认框
            if (oldDestCharPrefab != null)
            {
                if (!forceReplaceOld)
                {
                    if (!EditorUtility.DisplayDialog("提示", $"{prefabName}的Prefab已经存在,是否替换?", "替换", "跳过"))
                    {
                        return;
                    }
                }
                else
                {
                    Debug.LogWarning($"预设{destAssetPath}已存在，已执行替换。");
                }
            }

            string animatorName = string.Empty;
            if (withAnimator)
            {
                // 生成动画状态机
                var animatorPath = AnimatorEditorMenu.GenAnimatorByType(basePath, genPrefabType);
                if (string.IsNullOrEmpty(animatorPath))
                {
                    withAnimator = false;
                }
                else
                {
                    animatorName = Path.GetFileName(animatorPath);
                }
            }

            string modelObjPath = GetArtModeResPath();
            if (!File.Exists(modelObjPath))
            {
                Debug.LogError($"指定路径【{modelObjPath}】不存在，生成Prefab失败!");
                return;
            }

            var modelFbxObj = AssetDatabase.LoadAssetAtPath<GameObject>(modelObjPath);
            if (modelFbxObj == null)
            {
                Debug.LogError($"模型文件【{modelObjPath}】加载失败，生成Prefab失败!");
                return;
            }

            //动画状态机路径
            string animationCtrlPath = withAnimator ? Path.Combine(basePath, animatorName) : string.Empty;
            //生成GameObject
            GameObject rootObj = GenPrefabInternal(entityName, prefabName, modelFbxObj, animationCtrlPath, withAnimator);
            if (rootObj == null) return;

            var rPlayableDirector = rootObj.GetComponent<PlayableDirector>();
            if (rPlayableDirector == null)
            {
                rPlayableDirector = rootObj.AddComponent<PlayableDirector>();
            }

            rPlayableDirector.playOnAwake = false;

            if (rootObj.GetComponent<ExSignalReceiverBinding>() == null)
            {
                rootObj.AddComponent<ExSignalReceiverBinding>();
            }

            var rCCtrl = rootObj.GetComponent<CharacterController>();
            if (rCCtrl == null)
            {
                rCCtrl = rootObj.AddComponent<CharacterController>();
            }
            
            //生成动作视效播放套件
            GenAnimatorVFXPlayKit(rootObj);
            //绑定挂点
            GenBindRoot(rootObj, oldDestCharPrefab);
            KeepOldCollider(rootObj, oldDestCharPrefab);

            rCCtrl.height = 5;
            rCCtrl.center = Vector3.up * 2.5f;


            //保存Prefab
            GameObject prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(rootObj, destAssetPath, InteractionMode.AutomatedAction, out var success);
            Selection.activeObject = prefab;

            if (success)
            {
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
            else
            {
                Debug.LogError($"保存Prefab失败:[{prefabName}]");
            }

            UnityEngine.Object.DestroyImmediate(rootObj);
        }

        protected override void GenPrefabExtra(GameObject rootObj, GameObject modelObj)
        {
            base.GenPrefabExtra(rootObj, modelObj);
            var rBehaviorComp = rootObj.GetComponent<BehaviorFeatureComp>();
            if (rBehaviorComp)
            {
                rBehaviorComp.defaultTimelineAsset = AssetDatabase.LoadAssetAtPath<TimelineAsset>
                    ("Assets/Res/22_Render/Timeline/GlobalCharacterEffectTimeline.playable");
            }
        }

        public override string GetArtModeResPath()
        {
            return base.GetArtModeResPath();
        }

    }
}
